<?php

namespace XinLian;

use GuzzleHttp\Client;

class Tool
{
    /**
     * @introduce 获取13时间戳
     * @return float
     * @Date 2022/1/27
     * @author yanglei
     */
    public static function getUnixTimestamp ()
    {
        list($s1, $s2) = explode(' ', microtime());
        return (float)sprintf('%.0f',(floatval($s1) + floatval($s2)) * 1000);

    }
    /**
     * 创建签名
     * @param array $params 参与签名的数据
     * @param string $signKey 签名key
     * @return string
     */
    public static function createSign(array $params, string $signKey = ''):string
    {
        if (is_object($params)) { //对象转数组
            $params = json_decode(json_encode($params), true);
        }
        if (!empty($signKey)) {
            $params['sign_key'] = $signKey;
        }
        ksort($params);
        $formatData = [];
        foreach ($params as $k => $v) {
            if (is_array($v) || is_object($v)) {
                $v = json_encode($v,JSON_UNESCAPED_UNICODE);
            }
            if ((!empty($v) || (string)$v === '0') && $k != 'sign') {
                $formatData[] = "$k=$v";
            }
        }
        $signStr = implode('&', $formatData);
        return md5($signStr);
    }

    /**
     * @introduce http post请求
     * @param $url string 请求地址
     * @param $data array 参数
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function http(string $url, array $data){
        // 创建HTTP客户端实例
        $client = new Client(['timeout' => 60, 'verify' => false]);
        $headers = ['Content-Type'=>"application/json"];
        // 发送POST请求
        $response = $client->request('POST', $url,
            ['headers'=>$headers,'json' => $data]
        );
        return $response;
    }
}